package com.yuchen.advsdk.util;

import android.util.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.crypto.Cipher;

public class RSAUtil {
    /**RSA算法*/
    public static final String RSA = "RSA";
    /**加密方式，android的*/
//  public static final String TRANSFORMATION = "RSA/None/NoPadding";
    /**加密方式，标准jdk的*/
    public static final String TRANSFORMATION = "RSA/None/PKCS1Padding";

//    /** 使用公钥加密 */
//    public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
//        // 得到公钥对象
//        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
//        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//        PublicKey pubKey = keyFactory.generatePublic(keySpec);
//        // 加密数据
//        Cipher cp = Cipher.getInstance(TRANSFORMATION);
//        cp.init(Cipher.ENCRYPT_MODE, pubKey);
//        return cp.doFinal(data);
//    }

    /** 使用私钥解密 */
    public static String decryptByPrivateKey(String encrypted, String privateKey){
        try{
            // 得到私钥对象
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(privateKey,Base64.DEFAULT));
            KeyFactory kf = KeyFactory.getInstance(RSA);
            PrivateKey keyPrivate = kf.generatePrivate(keySpec);
            // 解密数据
            Cipher cp = Cipher.getInstance(TRANSFORMATION);
            cp.init(Cipher.DECRYPT_MODE, keyPrivate);
            byte[] arr = cp.doFinal(Base64.decode(encrypted,Base64.DEFAULT));
            return new String(arr);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
